//
//  SAInventoryDetailVC.m
//  yidiantong
//
//  Created by 黄志刚 on 2020/11/4.
//

#import "SAInventoryDetailVC.h"
#import "UILabel+NSMutableAttributedString.h"
#import "SAInventoryListModel.h"
#import "SAStockPreviewDetailAPI.h"
#import "SAInventoryDetailModel.h"
#import "SAInventoryDetailCell.h"
#import "SAInventoryWaterView.h"
#import "YBImageBrowser.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "SAEditShopVC.h"
#import "SAProductOverModel.h"
#import "SAStockCheckSaveOrUpdateAPI.h"

@interface SAInventoryDetailVC ()<UITableViewDataSource, UITableViewDelegate, HTTPAPIDelegate,YBImageBrowserDataSource>

@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UILabel *topTitleLab;
@property (nonatomic, strong) NSString *productId;
@property (nonatomic, strong) NSString *merchantId;
@property (nonatomic, strong) UIView *whiteView;
@property (nonatomic, strong) UIImageView *imageV;
@property (nonatomic, strong) UILabel *countLab;
@property (nonatomic, strong) UILabel *totalLab;
@property (nonatomic, strong) SAStockPreviewDetailAPI *stockPreviewDetailAPI;
@property (nonatomic, strong) NSMutableArray<SAInventoryDetailList *> *dataMarr;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *inventoryBtn;
@property (nonatomic, strong) UIView *redView;
@property (nonatomic, strong) SAInventoryDetailModel *detailModel;
@property (nonatomic, strong) NSArray *imageList;
@property (nonatomic, strong) UIButton *editBtn;
@property (nonatomic, strong) SAStockCheckSaveOrUpdateAPI *stockCheckSaveOrUpdateAPI;

@end

@implementation SAInventoryDetailVC

-(instancetype)initWithProductId:(NSString *)productId AndMerchantId:(NSString *)merchantId {
    if (self = [super init]) {
        self.productId = productId;
        self.merchantId = merchantId;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.stockPreviewDetailAPI == api) {
        SAInventoryDetailModel *model = [SAInventoryDetailModel mj_objectWithKeyValues:data[@"data"]];
        self.dataMarr = model.skuListVOS;
        self.detailModel = model;
        self.topTitleLab.text = [NSString stringWithFormat:@"%@\n%@",model.productCode,model.productName];
        self.view.backgroundColor = kLineColor;
        [self.topTitleLab setAttributedStringWithSubString:model.productName color:[UIColor whiteColor] font:kFont(13)];
        self.countLab.text = [NSString stringWithFormat:@"总库存:%0.f",model.subtotal];
        self.totalLab.text = [NSString stringWithFormat:@"总成本:%0.2f",model.stockCost/100];
        NSString *newUrl = [[model.img componentsSeparatedByString:@","][0] stringByReplacingOccurrencesOfString:@"?x-oss-process=style/thumbnail" withString:@""];
        NSString *imageUrl = [NSString stringWithFormat:@"%@?x-oss-process=image/resize,l_100",newUrl];
        [self.imageV sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"shop_placeholderImg"]];
        [self.tableView reloadData];
        for (SAInventoryDetailList *list in self.dataMarr) {
            list.beforeStock = list.stock;
        }
        
        NSString *productViewCostPrice = [NSString stringWithFormat:@"%@",[SAValueManger shareInStance].userInfo.menuList[1][@"perms"][@"productViewCostPrice"]];
        if ([productViewCostPrice isEqualToString:@"1"]) {
            self.totalLab.text = [NSString stringWithFormat:@"总成本:******"];
        }
    }else if (self.stockCheckSaveOrUpdateAPI == api) {
        self.editBtn.selected = NO;
        [_editBtn setTitle:@"编辑" forState:UIControlStateNormal];
        [Prompt popPromptViewWithMsg:@"修改成功" duration:2];
        [self.stockPreviewDetailAPI sendRequestToServerWithActivityViewAndMask:GET];
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    
}

#pragma mark - UITableView Delegate & DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataMarr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SAInventoryDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SAInventoryDetailCell" forIndexPath:indexPath];
    cell.isEdit = self.editBtn.isSelected;
    cell.model = self.dataMarr[indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(35);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kScaleNum(0.01);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return SafeFooterHeight;
}

#pragma mark - event
- (void)switchAction:(UISwitch *) s1 {
    if (s1.on == YES) {
        self.stockPreviewDetailAPI.filterZero = @"1";
        [self.stockPreviewDetailAPI sendRequestToServerWithActivityViewAndMask:GET];
    }else{
        self.stockPreviewDetailAPI.filterZero = @"0";
        [self.stockPreviewDetailAPI sendRequestToServerWithActivityViewAndMask:GET];
    }
}

-(void)clickedInventoryBtn {
    SAInventoryWaterView *waterView = [SAInventoryWaterView shareCornView];
    [waterView loadData:self.detailModel.productId MerchantId:self.merchantId Size:@"" Colour:@""];
    [waterView showView:self];
}

-(void)clickedListBtn {
    SAEditShopVC *pushVC = [[SAEditShopVC alloc] init];
    SAProductOverModel *model = [SAProductOverModel new];
    model.productId = [self.detailModel.productId integerValue];
    model.productCode = self.detailModel.productCode;
    model.productName = self.detailModel.productName;
    pushVC.productOverModel = model;
    [self.navigationController pushViewController:pushVC animated:YES];
}

-(void)clickedEditBtn {
    [self.view endEditing:YES];
    if (self.editBtn.selected != YES) {
        self.editBtn.selected = YES;
        [_editBtn setTitle:@"保存" forState:UIControlStateNormal];
        [self.tableView reloadData];
    }else {
        NSMutableDictionary *mdic = [NSMutableDictionary dictionary];
        NSMutableArray *productSkuFormArr = [NSMutableArray array];
        mdic[@"productSkuForms"] = productSkuFormArr;
        NSMutableDictionary *skuMdic = [NSMutableDictionary dictionary];
        skuMdic[@"productCode"] = self.detailModel.productCode;
        skuMdic[@"productId"] = self.detailModel.productId;
        skuMdic[@"productName"] =self.detailModel.productName;
        NSMutableArray *skuMarr = [NSMutableArray array];
        skuMdic[@"skuForms"] = skuMarr;
        [productSkuFormArr addObject:skuMdic];
        NSInteger total = 0;
        for (SAInventoryDetailList *model in self.dataMarr) {
            if (model.stock.length == 0) {
                [Prompt popPromptViewWithMsg:@"库存不能为空!" duration:2];
                return;
            }
            NSString *stockUp = model.stockUp;
            NSString *stockDown = model.stockDown;
            if ([model.stockUp isEqualToString:@"null"]) {
                stockUp = @"";
            }
            if ([model.stockDown isEqualToString:@"null"]) {
                stockDown = @"";
            }
            if (stockUp.length > 0 && stockDown.length > 0){
                if ([model.stockUp integerValue] > [model.stockDown integerValue]) {
                    
                }else {
                    [Prompt popPromptViewWithMsg:@"库存上限必须大于下限!" duration:2];
                    return;
                }
            }
            total += [model.stock integerValue];
            NSMutableDictionary *skuFormMdic = [NSMutableDictionary dictionary];
            skuFormMdic[@"afterStock"] = model.stock;
            skuFormMdic[@"beforeStock"] = model.beforeStock;
            skuFormMdic[@"colourId"] = model.colourId;
            skuFormMdic[@"colourName"] = model.colourName;
            skuFormMdic[@"diffStock"] = [NSString stringWithFormat:@"%zd",[model.stock integerValue] - [model.beforeStock integerValue]];
            skuFormMdic[@"lowerStock"] = stockDown;
            skuFormMdic[@"sizeId"] = model.sizeId;
            skuFormMdic[@"sizeName"] = model.sizeName;
            skuFormMdic[@"skuId"] = model.skuId;
            skuFormMdic[@"upperStock"] = stockUp;
            [skuMarr addObject:skuFormMdic];
        }
        NSString *totalAfterStock = [NSString stringWithFormat:@"%0.f",self.detailModel.subtotal];
        NSString *totalBeforeStock = [NSString stringWithFormat:@"%zd",total];;
        mdic[@"totalAfterStock"] = totalAfterStock;
        mdic[@"totalBeforeStock"] = totalBeforeStock;
        mdic[@"totalDiffStock"] = [NSString stringWithFormat:@"%zd",[totalBeforeStock integerValue] - [totalAfterStock integerValue]];
        mdic[@"isBatch"] = @"1";
        
        self.stockCheckSaveOrUpdateAPI.coverParameters = mdic;
        [self.stockCheckSaveOrUpdateAPI sendRequestToServerWithActivityViewAndMask:POST];
    }
}

-(void)clickedImageV {
    if (self.detailModel.imgList.count > 0) {
        self.imageList = self.detailModel.imgList;
        YBImageBrowser *browser = [YBImageBrowser new];
        browser.dataSourceArray = self.imageList;
        browser.dataSource = self;
        browser.currentPage = 0;
        [browser show];
    }else {
        [Prompt popPromptViewWithMsg:@"该商品没有图片" duration:2];
    }
}

//YBImageBrowserDataSource 代理实现赋值数据
- (NSInteger)yb_numberOfCellsInImageBrowser:(YBImageBrowser *)imageBrowser {
    return self.imageList.count;
}

- (id<YBIBDataProtocol>)yb_imageBrowser:(YBImageBrowser *)imageBrowser dataForCellAtIndex:(NSInteger)index {
    NSString *urlStr = [self.imageList objectAtIndex:index];
    YBIBImageData *data = [YBIBImageData new];
    data.imageURL = [NSURL URLWithString:urlStr];
    return data;
}

#pragma mark - initUI
-(void)initUI {
    [self setNavigationItemBackBBI:@"" AndTitle:@""];
    [self setBgImage:nil];
    [self addRightViews:@[self.topView]];
    
    NSMutableArray *menuList = [SAValueManger shareInStance].userInfo.menuList;
    NSString *productModifyProduct = [NSString stringWithFormat:@"%@",menuList[1][@"perms"][@"productModifyProduct"]];
    if (![productModifyProduct isEqualToString:@"1"]) {
        UIButton *listBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        listBtn.frame = CGRectMake(kScaleNum(312 - 60), 0, kScaleNum(60), kScaleNum(44));
        [listBtn setImage:[UIImage imageNamed:@"Inventory_edit"] forState:UIControlStateNormal];
        [listBtn addTarget:self action:@selector(clickedListBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.topView addSubview:listBtn];
    }
    
    [self.topView addSubview:self.topTitleLab];
    [self.view addSubview:self.whiteView];
    [self.whiteView addSubview:self.imageV];
    [self.whiteView addSubview:self.countLab];
    [self.whiteView addSubview:self.totalLab];
    [self.whiteView addSubview:self.inventoryBtn];
    
    NSString *stockModify = [NSString stringWithFormat:@"%@",menuList[3][@"perms"][@"stockModify"]];
    if (![stockModify isEqualToString:@"1"]) {
        [self.view addSubview:self.editBtn];
    }
    
    [self.view addSubview:self.redView];
    [self.view addSubview:self.tableView];
    
    self.stockPreviewDetailAPI.filterZero = @"0";
    self.stockPreviewDetailAPI.productId = self.productId;
    self.stockPreviewDetailAPI.merchantId = self.merchantId;
    [self.stockPreviewDetailAPI sendRequestToServerWithActivityViewAndMask:GET];
    
    if ([self.merchantId integerValue] != [SAValueManger shareInStance].userInfo.merchantId) {
        self.editBtn.userInteractionEnabled = NO;
        [self.editBtn setTitleColor:kLightgGrayColor forState:UIControlStateNormal];
        self.editBtn.layer.borderColor = kLightgGrayColor.CGColor;
    }
}

#pragma mark - lazy
-(UIView *)topView {
    if (!_topView) {
        _topView = [[UIView alloc] initWithFrame:SARectMake(63, 0, 312, 44)];
    }
    return _topView;
}

-(UILabel *)topTitleLab {
    if (!_topTitleLab) {
        _topTitleLab = [[UILabel alloc] initWithFrame:SARectMake(0, 0, 249, 44)];
        _topTitleLab.font = kFont(16);
        _topTitleLab.textColor = [UIColor whiteColor];
        _topTitleLab.numberOfLines = 0;
        _topTitleLab.textAlignment = NSTextAlignmentCenter;
    }
    return _topTitleLab;
}

-(UIView *)whiteView {
    if (!_whiteView) {
        _whiteView = [[UIView alloc] initWithFrame:SARectMake(0, StatusHeight, kBaseScreenWidth, 81)];
        _whiteView.backgroundColor = [UIColor whiteColor];
    }
    return _whiteView;
}

-(UIImageView *)imageV {
    if (!_imageV) {
        _imageV = [[UIImageView alloc] initWithFrame:SARectMake(30, 11, 53, 59)];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickedImageV)];
        _imageV.userInteractionEnabled = YES;
        _imageV.contentMode = UIViewContentModeScaleAspectFit;
        _imageV.clipsToBounds = YES;
        [_imageV setContentScaleFactor:[[UIScreen mainScreen] scale]];
        [_imageV addGestureRecognizer:tap];
    }
    return _imageV;
}

-(UILabel *)countLab {
    if (!_countLab) {
        _countLab = [[UILabel alloc] initWithFrame:SARectMake(93, 20, 140, 20)];
        _countLab.font = kFont(14);
        _countLab.textColor = kBlackColor;
        _countLab.textAlignment = NSTextAlignmentLeft;
    }
    return _countLab;
}

-(UILabel *)totalLab {
    if (!_totalLab) {
        _totalLab = [[UILabel alloc] initWithFrame:SARectMake(93, 41, 140, 20)];
        _totalLab.font = kFont(14);
        _totalLab.textColor = kBlackColor;
        _totalLab.textAlignment = NSTextAlignmentLeft;
    }
    return _totalLab;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight + 156), kScreenWidth, kScreenHeight - kScaleNum(StatusHeight + 156)) style:UITableViewStylePlain];
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
        _tableView.backgroundColor = kLineColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[SAInventoryDetailCell class] forCellReuseIdentifier:@"SAInventoryDetailCell"];
    }
    return _tableView;
}

-(SAStockPreviewDetailAPI *)stockPreviewDetailAPI {
    if (!_stockPreviewDetailAPI) {
        _stockPreviewDetailAPI = [SAStockPreviewDetailAPI apiWithDelegate:self];
    }
    return _stockPreviewDetailAPI;
}

-(NSMutableArray<SAInventoryDetailList *> *)dataMarr {
    if (!_dataMarr) {
        _dataMarr = [NSMutableArray array];
    }
    return _dataMarr;
}

-(UIButton *)inventoryBtn {
    if (!_inventoryBtn) {
        _inventoryBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _inventoryBtn.frame = SARectMake(295, 26, 60, 29);
        [_inventoryBtn setTitle:@"库存流水" forState:UIControlStateNormal];
        [_inventoryBtn setTitleColor:kBuleColor forState:UIControlStateNormal];
        _inventoryBtn.layer.cornerRadius = kScaleNum(3);
        _inventoryBtn.layer.borderWidth = kScaleNum(1);
        _inventoryBtn.layer.borderColor = kBuleColor.CGColor;
        _inventoryBtn.titleLabel.font = kFont(13);
        [_inventoryBtn addTarget:self action:@selector(clickedInventoryBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _inventoryBtn;
}

-(UIButton *)editBtn {
    if (!_editBtn) {
        _editBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _editBtn.frame = SARectMake(305, StatusHeight + 91, 50, 25);
        [_editBtn setTitle:@"编辑" forState:UIControlStateNormal];
        [_editBtn setTitleColor:kRedColor forState:UIControlStateNormal];
        _editBtn.layer.cornerRadius = kScaleNum(3);
        _editBtn.layer.borderWidth = kScaleNum(1);
        _editBtn.layer.borderColor = kRedColor.CGColor;
        _editBtn.titleLabel.font = kFont(13);
        [_editBtn addTarget:self action:@selector(clickedEditBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _editBtn;
}

-(UIView *)redView {
    if (!_redView) {
        _redView = [[UIView alloc] initWithFrame:SARectMake(0, StatusHeight + 126, kBaseScreenWidth, 30)];
        UIImageView *imageV = [[UIImageView alloc] initWithFrame:SARectMake(0, 0, kBaseScreenWidth, 30)];
        imageV.backgroundColor = kTextBgColor;
        [_redView addSubview:imageV];
        NSArray *arr = @[@"颜色", @"尺码", @"库存", @"库存上限", @"库存下限"];
        NSArray *arr2 = @[@"20", @"80", @"150", @"210", @"290"];
        NSArray *arr3 = @[@"55", @"65", @"60", @"75", @"75"];
        for (int i = 0; i < arr.count; i++) {
            NSInteger x = [arr2[i] integerValue];
            NSInteger w = [arr3[i] integerValue];
            UILabel *titleLab = [[UILabel alloc] initWithFrame:SARectMake(x, 0, w, 30)];
            titleLab.text = arr[i];
            titleLab.textColor = kTextColor;
            titleLab.font = kFont(15);
            titleLab.textAlignment = NSTextAlignmentCenter;
            [_redView addSubview:titleLab];
            
            if ( i == 0) {
                titleLab.textAlignment = NSTextAlignmentLeft;
            }
        }
    }
    return _redView;
}

-(SAStockCheckSaveOrUpdateAPI *)stockCheckSaveOrUpdateAPI {
    if (!_stockCheckSaveOrUpdateAPI) {
        _stockCheckSaveOrUpdateAPI = [SAStockCheckSaveOrUpdateAPI apiWithDelegate:self];
    }
    return _stockCheckSaveOrUpdateAPI;
}

@end
